/*
 * @Author: your name
 * @Date: 2021-09-04 19:19:31
 * @LastEditTime: 2021-09-27 21:13:13
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \node\libs\tools\wechat.js
 */
import { Req } from "./Tools"
const config = require("config-lite")(__dirname);
const fs = require("fs");
import rds from "../redis/redis";
import mysql from "../sqlcmd/mysql"
let cli = new rds(config.redis.host, config.redis.port, config.redis.password);

export default class WX {
   private static async getAccessToken() {
      let result: any = await Req.get(`https://api.weixin.qq.com/cgi-bin/token`, { grant_type: 'client_credential', appid: config.mpWeixinRz.AppID, secret: config.mpWeixinRz.AppSecret });
      return JSON.parse(result).access_token;
   }
   public static async AccessToken() {
      let r = await cli.get(config.mpWeixinRz.AppID);
      try {
         let time = new Date(parseInt(r.split("|")[1]));
         console.log(r);

         console.log(r.split("|")[1]);
         let shuzi = (new Date().getTime() - time.getTime()) / 1000
         if (shuzi >= 7000) {
            let result = await WX.getAccessToken();
            await cli.set(config.mpWeixinRz.AppID, `${result}|${new Date().getTime()}`);
            return result;
         } else {
            return r.split("|")[0];
         }
      } catch {
         let result = await WX.getAccessToken();
         await cli.set(config.mpWeixinRz.AppID, `${result}|${new Date().getTime()}`);
         return result;
      }
   }
   public static async NoticeKF(openid, id, type, org, err_msg, status) {
      let atk = await WX.AccessToken();
      var data = `{
         "touser": "${openid}",
         "template_id": "5x2sZTMDqGYBgEUyw2L8wGgtQDVqJZ8iC-_EKXKcTLE",
         "page": "pages/thingsdetail/thingsdetail?id=${id}&name=${name}",
         "data": {
             "thing1": {
                 "value": "${type}"
             },
             "thing3": {
               "value": "${(status == 1 || status == "1") ? '通过' : '不通过'}"
             },"thing4": {
               "value": "${org}"
             },
             "time5": {
                 "value": "${mysql.ConvertDate(new Date())}"
             }
         }
       }`;
      var r = await Req.post(`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${atk}`, JSON.parse(data));
      return r;
   }

   public static async getQrCode() {
      let atk: any = await WX.AccessToken();
      console.log(atk);
      var ti = [18]
      for (var i = 1; i < 10; i++) {
         let image: any = Req.pipe(`https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=${atk}`, { path: `pages/zhengcedetail/zhengcedetail?id=${i}` }, i);

      }
      //let bf=Buffer.from(image,"utf-8");
      //fs.writeFile('1.jpg', bf,(err)=>{console.log(err)});
      return 1;
   }
}